package com.example.huancun.service;

import com.example.huancun.entity.Comment;
import com.example.huancun.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Optional;


@Service
public class CommentService{

@Autowired
private CommentRepository commentRepository;
//public Comment findById(int comment_id){
//        Optional<Comment> optional=commentRepository.findById(comment_id);
//        if(optional.isPresent()){
//                return optional.get();
//        }
//        return null;
//}
//public Comment updateComment(Comment comment){
//        commentRepository.updateComment(comment.getAuthor(),comment.getId());
//        return comment;
//}
//public void deleteComment(int comment_id){
//        commentRepository.deleteById(comment_id);
//}


@Cacheable( cacheNames = "comment",unless="#result==null")
public Comment findCommentById(Integer id){
        Optional<Comment> comment = commentRepository.findById(id);
        if (comment.isPresent()){
        return comment.get();
        }
        return null;
        }
@CachePut(cacheNames = "comment", key = "#result.id")
public Comment updateComment(Integer id, String content){
        Comment comment = findCommentById(id);
        comment.setContent(content);
        commentRepository.updateComment(id, content);
        return comment;
        }
@CacheEvict(cacheNames = "comment")
public void deleteCommentById(Integer id){
        commentRepository.deleteById(id);
        }

        }